<template>
	<view :style="mix_diyStyle">
  <view
    class="shake_main"
    :style="{
      backgroundImage: 'url(' + backgroundImg + ')',
      minHeight: screenHeight + 'px'
    }"
  >
    <view class="shake_main_con" :style="{marginTop:`${statusBarHeight}px`}">
      <view class="shake_title bg_style">
        <view class="right_intro">
          <view class="right_item" @click="open">{{ $L('活动详情') }}</view>
        </view>
      </view>
      <view class="shake_table">
        <view class="shake_table_con bg_style">
          <view class="shake_center flex_column_center_center">
            <block
              v-if="reactAcDetail.acState && reactAcDetail.acState.flag == 1"
            >
              <text v-if="myInt.remainNum > 0">{{ myInt.remainNum }}</text>
              <text>{{
                myInt.remainNum > 0 ? $L('剩余抽奖次数') : $L('抽奖次数已用尽')
              }}</text>
            </block>
          </view>
          <view class="flex_column_center_center">
            <view
              :class="{ sha_ca: true, shake: isShake, bg_style: true }"
              :style="{ backgroundImage: 'url(' + rollImg + ')' }"
            ></view>
          </view>
        </view>
      </view>

      <view
        :class="[
          'self_info',
          lotDetail.integralUse > 0
            ? 'flex_row_between_center'
            : 'flex_row_center_center'
        ]"
      >
        <view class="info_btn" v-if="lotDetail.integralUse > 0"
          >{{ $L('我的积分') }}：{{ myInt.integral }}{{ $L('积分') }}
        </view>
        <view class="info_btn" @click="showRes">{{ $L('我的中奖记录') }}</view>
      </view>

      <view class="shake_bot">
        <view class="shake_bot_con bg_style">
          <view
            class="roll_in_list flex_column_between_center"
            v-if="reactAcDetail.acState && reactAcDetail.acState.flag == 1"
          >
            <view class="flex_row_center_center roll_title_con">
              <image :src="imgUrl + 'dot_left.png'" mode="aspectFit"></image>
              <view class="roll_title">{{ $L('中奖名单') }}</view>
              <image :src="imgUrl + 'dot_left.png'" mode="aspectFit"></image>
            </view>
            <view
              class="roll_swiper flex_row_center_center bg_style_cover"
              :style="{
                backgroundImage: 'url(' + imgUrl + 'scra_print_bg.png)'
              }"
            >
              <swiper
                :indicator-dots="false"
                :autoplay="true"
                :interval="5000"
                :duration="1000"
                :disable-touch="true"
                :vertical="true"
                circular
                @change="change"
                display-multiple-items="3"
              >
                <swiper-item v-for="(item, index) in lotList" :key="index">
                  <view
                    :class="{ roll_swiper_item: true, sel: index == current }"
                    >{{ $L('恭喜') }} {{ item.memberNameHide }} {{ $L('获得')
                    }}{{ item.prizeName }}
                  </view>
                </swiper-item>

                <block v-if="3 - lotList.length > 0">
                  <swiper-item v-for="i in 3 - lotList.length" :key="i"> </swiper-item>
                </block>
              </swiper>
            </view>
          </view>
          <view class="roll_in_list flex_column_between_center" v-else>
            <view class="flex_row_center_center roll_title_con">
              <view class="roll_title">{{ reactAcDetail.acState.desc }}</view>
            </view>
            <view class="flex_row_center_center">
              <view class="roll_title_end">{{
                reactAcDetail.acState.time
              }}</view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <popInfo ref="popInfo" @revive="revive"></popInfo>

    <uni-popup ref="shake" type="center" @change="popChange">
      <view
        class="shake_box bg_style_start"
        :style="{ backgroundImage: 'url(' + imgUrl + 'shake_integral.png)' }"
        v-if="rollRes == 'roll_on'"
      >
        <view class="flex_column_start_center box_1">
          <view class="text1">{{ $L('恭喜您获得') }}</view>
          <view class="text2">
            <block v-if="lotResult.prizeType == 1">
              <text>{{ parseFloat(lotResult.description) }}</text>
              <text>{{ $L('积分') }}</text>
            </block>
            <block
              v-if="lotResult.couponType == 1 || lotResult.couponType == 3"
            >
              <text>{{ parseFloat(lotResult.description) }}</text>
              <text>{{ `${$L('元')}${$L('优惠券')}` }}</text>
            </block>
            <block v-if="lotResult.couponType == 2">
              <text>{{ parseFloat(lotResult.publishValue / 10) }}</text>
              <text>{{ `${$L('折')}${$L('优惠券')}` }}</text>
            </block>
          </view>
        </view>
        <view class="box_2">
          <view class="desc flex_column_between_center">
            <view class="desc_desc"
              >{{
                lotResult.prizeType == 1
                  ? $L('积分已存入“我的-积分”')
                  : $L('优惠券已存入“我的-优惠券”')
              }}
            </view>
            <view class="desc_button flex_row_between_center">
              <view class="btn1" @click="shareAc">{{ $L('分享活动') }}</view>
              <view class="btn2" @click="deployUse">{{ $L('立即查看') }}</view>
            </view>
          </view>
        </view>
      </view>
      <view
        class="shake_box bg_style"
        :style="{ backgroundImage: 'url(' + imgUrl + 'shake_fail.png)' }"
        v-if="rollRes == 'roll_off'"
        @click="$refs.shake.close()"
      ></view>
      <view class="close flex_row_center_center">
        <view class="close_blank" @click="$refs.shake.close()">
          <image :src="imgUrl + 'close.png'" mode="aspectFit"></image>
        </view>
      </view>
    </uni-popup>
  </view>
	</view>
</template>

<script>
import { arrCom } from '@/utils/common.js'
import popInfo from '../component/popInfo.vue'
import topHeader from '../component/topHeader.vue'
export default {
  components: {
    topHeader,
    popInfo
  },
  props: {
    lotDetail: {
      type: Object
    },
    userInt: {
      type: Object
    },
    drawId: {
      type: Number
    }
  },
  inject: ['openShare', 'getAcDetail'],
  computed: {
    reactAcDetail() {
      return this.isCreated ? this.getAcDetail() : {}
    },
    backgroundImg() {
      if (this.isCreated) {
        let { backgroundImageUrl } = this.lotDetail
        return backgroundImageUrl
          ? backgroundImageUrl
          : this.imgUrl + 'shake_lotte_bg.png'
      }
    },
    rollImg() {
      if (this.isCreated) {
        let { availableButtonImageUrl } = this.lotDetail
        return availableButtonImageUrl
          ? availableButtonImageUrl
          : this.imgUrl + 'sha_ca.png'
      }
    }
  },
  data() {
    return {
      imgUrl: getApp().globalData.imgUrl + 'lottery/',
      current: 0,
      isShake: false,
      global: {
        lastTime: 0, //此变量用来记录上次摇动的时间
        intervalTime: 400, // 两次摇一摇的间隔事件
        // #ifdef APP-PLUS || H5
        shakeSpeed: 3500, //设置阈值
        // #endif
        // #ifdef MP
        shakeSpeed: 500, //设置阈值
        // #endif
        lastX: 0,
        lastY: 0,
        lastZ: 0
      },
      isRevive: true,
      rollRes: '',
      showState: '',
      lotList: [],
      lotResult: {},
      myInt: {},
      acState: {},
      showTipOnce: true,
      screenHeight: 0,
      timer: null,
      shakes: 0,
      shakeState: 'stateNull',
      isCreated: false,
	  statusBarHeight:uni.getSystemInfoSync().statusBarHeight
    }
  },
  created() {
    this.isCreated = true
    this.getlotRecAsync()
    this.getlotInt().then((res) => {
      this.myInt = res
      if (this.myInt.remainNum == 0) {
        this.$api.msg(this.$L('您的抽奖次数已用完'))
      } else if (this.myInt.integral < this.lotDetail.integralUse) {
        this.$api.msg(this.$L('您的抽奖积分不足'))
      } else {
        let that = this

        // #ifdef H5
        let ua = window.navigator.userAgent.toLowerCase()
        if (ua.indexOf('like mac os x') > 0) {
          //IOS H5的摇一摇需要手动获取手机的动作权限
          if (window.DeviceMotionEvent) {
            let ua = window.navigator.userAgent.toLowerCase()
            var reg = /os [\d._]*/gi
            var verinfo = ua.match(reg)
            var version = (verinfo + '')
              .replace(/[^0-9|_.]/gi, '')
              .replace(/_/gi, '.')
            if (parseFloat(version) >= 13) {
              window.DeviceMotionEvent.requestPermission()
                .then((permissionState) => {
                  if (permissionState === 'granted') {
                    uni.startAccelerometer({
                      success(res) {
                        uni.onAccelerometerChange(that.startShake)
                      },
                      complete: (com) => {}
                    })
                  }
                })
                .catch((error) => {
                  uni.showModal({
                    content: that.$L('ios需要手动获取动作权限'),
                    success: (res) => {
                      if (res.confirm) {
                        that.iosShakeGranted()
                      }
                    }
                  })
                })
            }
          }
        } else {
          //安卓的H5不需要获取动作权限
          uni.startAccelerometer({
            success(res) {
              uni.onAccelerometerChange(that.startShake)
            },
            complete: (com) => {}
          })
        }
        // #endif

        // #ifdef APP-PLUS||MP-WEIXIN||MP-BAIDU||MP-TOUTIAO
        //而APP和微信小程序则不需要获取动作权限
        uni.startAccelerometer({
          success(res) {
            uni.onAccelerometerChange(that.startShake)
          },
          complete: (com) => {}
        })
        // #endif

        // #ifdef MP-ALIPAY
        my.startAccelerometer({
          interval: 'ui',
          success: () => {
            my.onAccelerometerChange(that.startShake)
          }
        })
        // #endif
      }
    })
  },

  mounted() {
    this.screenHeight = uni.getSystemInfoSync().windowHeight
  },

  beforeDestroy() {
    clearInterval(this.timer)
  },

  methods: {
    onShowAcc() {
      let that = this
      if (this.showState == 'screen' || this.showState == 'nav') {
        uni.startAccelerometer({
          success() {
            uni.onAccelerometerChange(that.startShake)
          }
        })
      }
    },

    iosShakeGranted() {
      let that = this
      if (typeof DeviceMotionEvent.requestPermission === 'function') {
        DeviceMotionEvent.requestPermission()
          .then((permissionState) => {
            if (permissionState === 'granted') {
              uni.startAccelerometer({
                success(res) {
                  uni.onAccelerometerChange(that.startShake)
                },
                complete: (com) => {}
              })
            }
          })
          .catch((error) => {})
      } else {
        // 处理常规的非iOS 13+设备
        console.log('处理常规的非iOS 13+设备')
      }
    },

    change(e) {
      this.current = e.detail.current + 1
    },
    open() {
      this.$refs.popInfo.open({}, 'acDetail')
    },

    showRes() {
      this.showState = 'nav'
      this.$Router.push({
        path: '/standard/lottery/lotRec',
        query: {
          drawId: this.lotDetail.drawId
        }
      })
    },
    startShake(acceleration) {
      if (!this.isRevive) {
        return
      }

      if (this.reactAcDetail.acState.flag != 1) {
        return
      }

      let nowTime = new Date().getTime() //记录当前时间
      //如果这次摇的时间距离上次摇的时间有一定间隔 才执行
      if (nowTime - this.global.lastTime > 300) {
        let diffTime = nowTime - this.global.lastTime
        this.global.lastTime = nowTime // 记录本次摇动时间，为下次计算摇动时间做准备
        let x = acceleration.x // 获取x轴数值，x轴为垂直于北轴，向东为正
        let y = acceleration.y // 获取y轴数值，y轴向正北为正
        let z = acceleration.z // 获取z轴数值，z轴垂直于地面，向上为正
        // 速度计算
        let speed =
          (Math.abs(
            x +
              y +
              z -
              this.global.lastX -
              this.global.lastY -
              this.global.lastZ
          ) /
            diffTime) *
          100000
        this.shakes = speed
        //如果计算出来的速度超过了阈值，那么就算作用户成功摇一摇
        if (speed > this.global.shakeSpeed) {
          this.isShake = true
          this.isRevive = false
          this.global.lastTime = nowTime
          uni.vibrateLong({})
          setTimeout(() => {
            uni.showLoading()
            this.doDraw()
          }, 2000)
        }
        this.global.lastX = x
        this.global.lastY = y
        this.global.lastZ = z
      }
    },
    popChange(e) {
      if (!e.show) {
        this.revive()
      }
    },
    revive() {
      if (this.lotResult.prizeType == 1)
        this.myInt.integral += parseInt(this.lotResult.description)
      this.isShake = false
      this.isRevive = true
    },
    async getlotRecAsync() {
      if (this.reactAcDetail.acState.flag != 1) {
        return
      }

      this.lotList = await this.getlotRec()
      this.timer = setInterval(async () => {
        let res = await this.getlotRec()
        if (res.length) {
          this.lotList.push(...arrCom(this.lotList, res, 'winId'))
        }
      }, 6000)
    },
    getlotRec() {
      return new Promise((resolve) => {
        this.$request({
          url: 'v3/promotion/front/draw/winList',
          data: {
            drawId: this.drawId
          }
        }).then((res) => {
          if ((res.state = 200)) {
            resolve(res.data)
          }
        })
      })
    },
    getlotInt() {
      return new Promise((resolve) => {
        this.$request({
          url: 'v3/promotion/front/draw/integral',
          data: {
            drawId: this.drawId
          }
        }).then((res) => {
          if ((res.state = 200)) {
            resolve(res.data)
          }
        })
      })
    },
    doDraw() {
      this.$request({
        url: 'v3/promotion/front/draw/doDraw',
        method: 'POST',
        data: {
          drawId: this.drawId
        }
      }).then((res) => {
        if (res.state == 200) {
          uni.hideLoading()
          this.lotResult = res.data
          this.rollRes = this.lotResult.isPrize == 1 ? 'roll_on' : 'roll_off'
          if (this.lotDetail.integralUse > 0) {
            this.myInt.integral -= this.lotDetail.integralUse
          }
          this.myInt.remainNum -= 1
          this.$refs.shake.open()
        } else {
          uni.hideLoading()
          this.$api.msg(res.msg)
        }
      })
    },
    shareAc() {
      this.$refs.shake.close()
      this.openShare()
    },
    deployUse() {
      let path =
        this.lotResult.prizeType == 1
          ? '/pages/user/myIntegral'
          : '/standard/coupon/myCoupon'
      this.$Router.push(path)
    }
  }
}
</script>

<style lang="scss" scoped>
uni-swiper {
  display: block;
  width: 636rpx;
  height: 150rpx;
}

uni-swiper-item {
  display: flex;
  align-items: center;
  justify-content: center;
}

/* #ifdef MP */
swiper {
  width: 636rpx !important;
  height: 150rpx !important;
}

swiper-item {
  display: flex;
  align-items: center;
  justify-content: center;
}

/* #endif */

.close {
  width: 100%;
  position: absolute;
  bottom: -140rpx;

  .close_blank {
    image {
      width: 55rpx;
      height: 55rpx;
    }
  }
}

.bg_style {
  background-position: center center;
  background-repeat: no-repeat;
  background-size: contain;
}

.bg_style_cover {
  background-position: center center;
  background-repeat: no-repeat;
  background-size: cover;
}

.bg_style_start {
  background-position: 0 0;
  background-repeat: no-repeat;
  background-size: contain;
}

.shake_main {
  margin: 0;
  /* #ifdef APP-PLUS */
  padding-top: calc(var(--status-bar-height) + 90rpx);
  /* #endif */
  /* #ifndef APP-PLUS */
  padding-top: 90rpx;
  /* #endif */
  padding-bottom: 20rpx;
  background-position: top;
  

  
  background-repeat: no-repeat;
  background-size: cover;

  .shake_main_con {
    position: relative;
  }

  .scra_st {
    margin-bottom: 32rpx;

    view {
      min-width: 320rpx;
      height: 50rpx;
      background: linear-gradient(
        90deg,
        #ffe155 0%,
        #f4e878 0%,
        #fff7b7 52%,
        #f3e578 100%
      );
      box-shadow: 0px 6px 3px 0px rgba(145, 41, 1, 0.41);
      text-align: center;
      line-height: 50rpx;
      border-radius: 25px;
      font-size: 30rpx;
      font-family: SourceHanSansCN;
      font-weight: 600;
      color: #d00908;
    }
  }

  .shake_table {
    margin-top: -150rpx;

    .shake_table_con {
      height: 700rpx;
      position: relative;
      padding: 20rpx;

      .shake_times {
        font-size: 28rpx;
        font-family: SourceHanSansCN;
        font-weight: bold;
        color: #bf4001;
        text-align: center;
        height: 70rpx;
        line-height: 70rpx;
      }

      .shake_center {
        margin-top: calc(100rpx - var(--status-bar-height));
        margin-bottom: 10rpx;
        line-height: 38rpx;
        padding-left: 1 0rpx;
        height: 110rpx;

        text:first-child {
          font-size: 44rpx;
          font-family: Microsoft YaHei;
          font-weight: 400;
          color: #5c0e7d;
        }

        text:last-child {
          margin-top: 20rpx;
          font-size: 22rpx;
          font-family: Microsoft YaHei;
          font-weight: 400;
          color: #610d85;
        }
      }

      .sha_ca {
        width: 384rpx;
        height: 283rpx;

        &.shake {
          animation: shake 1.5s;
          animation-timing-function: ease-in-out;
        }
      }

      @keyframes shake {
        0%,
        100% {
          transform: translateX(0);
        }

        5%,
        15%,
        25%,
        35%,
        45%,
        55%,
        65%,
        75%,
        85%,
        95% {
          // transform: translateX(-25px);
          transform: rotate(-15deg);
        }

        10%,
        20%,
        30%,
        40%,
        50%,
        60%,
        70%,
        80%,
        90% {
          // transform: translateX(25px);
          transform: rotate(15deg);
        }
      }

      .shake_desc {
        position: absolute;
        bottom: 30rpx;
        font-size: 22rpx;
        font-family: SourceHanSansCN;
        color: #bf4001;
        text-align: center;
        height: 50rpx;
        line-height: 50rpx;
      }
    }
  }

  .self_info {
    padding: 0 70rpx;

    .info_btn {
      font-size: 24rpx;
      font-family: SourceHanSansCN;
      font-weight: 500;
      color: #ffffff;
      border-radius: 25px;
      padding: 10rpx 22rpx;
      background: transparent;
      border: 1px solid #ffffff;
    }
  }

  .shake_title {
    margin-top: 30rpx;
    height: 373rpx;
  }

  .right_intro {
    display: flex;
    justify-content: flex-end;

    .right_item {
      width: 141rpx;
      height: 50rpx;
      background: #fcb82f;
      border-radius: 25rpx 0 0 25rpx;
      text-align: center;
      line-height: 50rpx;
      font-size: 26rpx;
      font-family: SourceHanSansCN;
      font-weight: 600;
      color: #ffffff;
    }
  }

  .shake_bot {
    padding: 0 40rpx;

    .shake_bot_con {
      height: 320rpx;
      padding: 20rpx 0;
      position: relative;
    }

    .bot_instruct {
      padding: 0 72rpx;

      view:first-child {
        text-align: center;
        font-size: 26rpx;
        font-family: SourceHanSansCN;
        font-weight: bold;
        color: #ab0100;
      }

      view:last-child {
        margin-top: 6rpx;
        font-size: 18rpx;
        font-family: SourceHanSansCN;
        font-weight: 400;
        color: #d13912;
      }
    }

    .roll_in_list {
      padding-top: 40rpx;
      width: 100%;

      .roll_title_con {
        image {
          width: 100rpx;
          height: 7px;

          &:last-child {
            transform: rotate(180deg);
          }
        }
      }

      .roll_title {
        padding-left: 8rpx;
        letter-spacing: 6px;
        text-align: center;
        font-size: 36rpx;
        font-family: zcoolqingkehuangyouti;
        font-weight: 600;
        color: #ffffff;
        margin: 0 10rpx;
      }

      .roll_title_end {
        color: #ffffff;
        margin-top: 10rpx;
      }

      .roll_swiper {
        margin-top: 20rpx;
        width: 640rpx;
        height: 176rpx;
      }

      .roll_swiper_item {
        text-align: center;
        font-size: 24rpx;
        font-family: SourceHanSansCN;
        font-weight: 400;
        color: #ffffff;
        opacity: 0.8;

        &.sel {
          color: #ffffff;
          font-weight: 600;
          font-size: 26rpx;
        }
      }
    }
  }
}

.shake_box {
  height: 544rpx;
  width: 664rpx;
  padding-top: 84rpx;

  .box_1 {
    position: relative;
    height: 182rpx;
    padding: 16rpx;

    .text1 {
      font-size: 20rpx;
      font-family: SourceHanSansCN;
      font-weight: 400;
      color: #d48b0b;
    }

    .text2 {
      font-family: SourceHanSansCN;
      font-weight: 500;
      color: #e13b00;

      text:first-child {
        font-size: 48rpx;
      }

      text:last-child {
        font-size: 24rpx;
      }
    }

    .text3 {
      position: absolute;
      bottom: 14rpx;
      font-size: 16rpx;
      font-family: SourceHanSansCN;
      font-weight: 400;
      color: #999999;
    }
  }

  .box_2 {
    .desc {
    }

    .desc_desc {
      height: 170rpx;
      line-height: 170rpx;
      text-align: center;
      font-size: 22rpx;
      font-family: SourceHanSansCN;
      font-weight: 400;
      color: #ffffff;
    }

    .desc_button {
      width: 60%;
      margin-top: 32rpx;

      .btn1 {
        width: 161rpx;
        height: 53rpx;
        background: linear-gradient(0deg, #fff0ca 0%, #ffe198 100%);
        border-radius: 10px;
        text-align: center;
        line-height: 53rpx;
        font-size: 23rpx;
        font-family: SourceHanSansCN;
        font-weight: 600;
        color: #d90826;
      }

      .btn2 {
        width: 161rpx;
        height: 53rpx;
        background: linear-gradient(
          0deg,
          #fce000 0%,
          #fed600 0%,
          #ff5d00 0%,
          #fb3e31 100%
        );
        border-radius: 10px;
        text-align: center;
        line-height: 53rpx;
        font-size: 23rpx;
        font-family: SourceHanSansCN;
        font-weight: 600;
        color: #ffffff;
      }
    }
  }
}
</style>
